package org.example.simplemanagementsystem.controller;


import org.example.simplemanagementsystem.pojo.Dept;
import org.example.simplemanagementsystem.pojo.Result;
import org.example.simplemanagementsystem.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


@RestController
@RequestMapping("/depts")
public class DeptController {
    private static final Logger log = LoggerFactory.getLogger(DeptController.class);
    @Autowired
    private DeptService deptService;

    /**
     * 查询所有部门的数据，并按时间降序排序
     * @return Result
     */
    @GetMapping
    public Result list() {
        log.info("查询全部的部门数据");
        List<Dept> deptList = deptService.findAll();

        return Result.success(deptList);
    }

    /**
     * 按指定的id删除部门
     */
    @DeleteMapping
    // @RequestParam 出参数是必须的；如果可以不需要@RequestParam(value="id",required=false)
    // 形参名和前端传递的参数名称一致可以直接省略@RequestParam
    public Result delete(@RequestParam("id") Integer id) {
        int rows = deptService.deleteById(id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.error("删除失败,该部门还有关联员工");
        }
    }
    /**
     * 新增部门
     */
    @PostMapping
    // JSON数据的键名与实体对象的属性名相同，并且使用@RequestBody注解标识
    public Result add(@RequestBody Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptService.add(dept);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id) {
        Dept dept = deptService.getInfo(id);
        return Result.success(dept);
    }
    @PutMapping
    public Result update(@RequestBody Dept dept) {
        deptService.update(dept);
        return Result.success();
    }
}
